<template>
    <view v-if="file">
       <FileCell :fileName="file.fileName" :fileType="file.extName" @confirm="downloadFile"></FileCell>
    </view>
</template>
<script setup>
import {ref} from 'vue';
import useApp from '@/hooks'
const { $ } = useApp();
import { watch } from "vue";
const file = ref(null)
const props = defineProps({
    fileId: {
        type: [String, Number]
    }
})
function queryFile() {
    $.request({
        url: '/ufs/file/' + props.fileId,
        method: 'get'
    }).then(res => {
        file.value = res.data;
    })
}
watch(() => props.fileId, () => {
    if (!$.isEmpty(props.fileId)) {
        queryFile();
    }
})

// 文件下载
function downloadFile() {
  uni.showLoading({
    title: "文件下载中~",
  });
  uni.downloadFile({
    url: $.api + "/ufs/download/"+props.fileId,
    header: {
      token: uni.getStorageSync("token"),
    },
    success: (res) => {
      console.log(res);
      var filePath = res.tempFilePath;
      let info = res.header["Content-Disposition"];
      console.log(info);
      var fileType = info.substring(info.lastIndexOf(".") + 1); //txt
      console.log(fileType);
      uni.openDocument({
        filePath: filePath,
        fileType: fileType,
        showMenu: true,
        success: function (res) {
          console.log("打开文档成功");
        },
        fail: (r) => {
          console.log(r);
          uni.showToast({
            title: "不支持小程序端查看",
            icon: "none",
          });
        },
      });
    },
    complete: (res) => {
      console.log(res);
      uni.hideLoading();
    },
  });
}
queryFile();
</script>